package com.unismc.wixindemo.web;


import com.unismc.wixindemo.entity.Data;
import com.unismc.wixindemo.service.ClientService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/wechat")
@Slf4j
public class WechatController {
	
	@Autowired
	private WxMpService wxMpService;

	
	@Autowired
	private ClientService clientService;


	
    @GetMapping("/authorize")
    public String authorize(){
    	Map<String, Object> resultMap = new HashMap<String, Object>();
        String url = "http://24w00244f7.zicp.vip/wechat/getOpenId";
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE,null);
        resultMap.put("redirectURL", redirectURL);
        return redirectURL;
    }

	@GetMapping("/releaseCode")
	public String releaseCode(){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String url = "http://24w00244f7.zicp.vip/wechat/releaseOpenId";
		String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE,null);
		resultMap.put("redirectURL", redirectURL);
		return redirectURL;
	}

	/**
	 * 获取openId
	 * @param code
	 * @param response
	 * @throws Exception
	 */
	@GetMapping("/releaseOpenId")
	public void getReleaseOpenId(@RequestParam("code") String code,
						 HttpServletResponse response) throws Exception {
		WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
		String openId = wxMpOAuth2AccessToken.getOpenId();
		response.sendRedirect("http://24w00244f7.zicp.vip/client/releaseBind.html?openId="+openId);
	}

    /**
     * 获取openId
     * @param code
     * @param response
     * @throws Exception
     */
    @GetMapping("/getOpenId")
    public void userInfo(@RequestParam("code") String code,
    		HttpServletResponse response) throws Exception {
    	WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
    	String openId = wxMpOAuth2AccessToken.getOpenId();
    	System.out.println("openId:"+openId);
    	//response.sendRedirect("http://24w00244f7.zicp.vip/client/bind.html?openId="+openId);
    }
    

    
    /**
     * MD5加密
     * @param plainText
     * @return
     */
	public String encryption(String plainText) {
		String re_md5 = new String();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

			re_md5 = buf.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return re_md5;
	}
	
	/**
	 *
	 * @param Authorization
	 * @param username
	 * @param projectMark
	 * @param title
	 * @param first
	 * @param keyword1
	 * @param keyword2
	 * @param keyword3
	 * @param remark
	 */
    @PostMapping("/sendEventTemplate")
    public void sendEventTemplate(@RequestParam("Authorization") String Authorization,
    		@RequestParam("username") String username,
    		@RequestParam("projectMark") String projectMark,
    		@RequestParam("title") String title,
    		@RequestParam("first") String first,
    		@RequestParam("keyword1") String keyword1,
    		@RequestParam("keyword2") String keyword2,
    		@RequestParam("keyword3") String keyword3,
    		@RequestParam("remark") String remark) {
    	System.out.println("告警");
    		Base64.Decoder decoder = Base64.getDecoder();
			try {
				String token = new String(decoder.decode(Authorization), "UTF-8");
				if(username.equals(token)) {
					Data data = new Data();
					data.setProjectMark(projectMark);
					data.setUsername(username);
					data.setTitle(title);
					data.setFirst(first);
					data.setKeyword1(keyword1);
					data.setKeyword2(keyword2);
					data.setKeyword3(keyword3);
					data.setRemark(remark);
					clientService.sendTemplate(data);
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
    }
    
    @PostMapping("/sendFlowTemplate")
    public void sendFlowTemplate(@RequestParam("Authorization") String Authorization,
    		@RequestParam("username") String username,
    		@RequestParam("projectMark") String projectMark,
    		@RequestParam("title") String title,
    		@RequestParam("first") String first,
    		@RequestParam("keyword1") String keyword1,
    		@RequestParam("keyword2") String keyword2,
    		@RequestParam("remark") String remark) {
    	if("故障进度".equals(title)) {
    		Base64.Decoder decoder = Base64.getDecoder();
			try {
				String token = new String(decoder.decode(Authorization), "UTF-8");
				if(username.equals(token)) {
					Data data = new Data();
					data.setProjectMark(projectMark);
					data.setUsername(username);
					data.setTitle(title);
					data.setFirst(first);
					data.setPerformance(keyword1);
					data.setTime(keyword2);
					data.setRemark(remark);
					clientService.sendTemplate(data);
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
    	}else {
    		Base64.Decoder decoder = Base64.getDecoder();
    		try {
    			String token = new String(decoder.decode(Authorization), "UTF-8");
    			if(username.equals(token)) {
    				Data data = new Data();
    				data.setProjectMark(projectMark);
    				data.setUsername(username);
    				data.setTitle(title);
    				data.setFirst(first);
    				data.setKeyword1(keyword1);
    				data.setKeyword2(keyword2);
    				data.setRemark(remark);
    				clientService.sendTemplate(data);
    			}
    		} catch (UnsupportedEncodingException e) {
    			e.printStackTrace();
    		}
    	}
    }

}
